import { login, logout, register,userList} from '@/api/service'
import { setUser,getUser, removeUser} from '@/utils/auth'

const state = {
 // token: getToken(),
  userInfo:{}
}
const mutations = {
  SET_TOKEN: (state, token) => {
      console.log("SET_TOKEN方法",token);
    state.token = token
  },
  SET_USERINFO: (state, info) => {
    //  console.log("SET_USERINFO方法",info);
    state.userInfo = info
  },
  REMOVE_TOKEN: (state, token) => {
    state.token =null;
  },
  REMOVE_USERINFO: (state, token) => {
    state.userInfo =null;
  },
}
const actions = {
  login({ commit }, userInfo) {
   return new Promise((resolve, reject) => {
      login(userInfo).then((response) =>{
        resolve(response) 
        setUser(response.data)//存放cookie
        commit('SET_USERINFO', Object.assign({},response.data))
      }).catch(error => reject(error))
    })
  },
  register({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      register(userInfo).then((response) =>{
         resolve(response)
        //  commit('SET_TOKEN', {});
        //  commit('SET_USERINFO', Object.assign({},userInfo,response))
       }).catch(error => reject(error))
     })
   },

  getUserList({ commit, state },data) {
    return new Promise((resolve, reject) => {
      userList(data).then((response) =>resolve(response)).catch(error => reject(error))
    })
  },

  getUserInfo({ commit, state },data) {
      commit('SET_USERINFO', data)
  },
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then((response) => {  
         commit('REMOVE_TOKEN', '')//移除token
         commit('REMOVE_USERINFO', '')//移除用户
         resolve(response);
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
